package com.Tread;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AB线程交替打印
 */
public class ABThread {

   private static final ReentrantLock lock  = new ReentrantLock();

   private static final Condition condition = lock.newCondition();


    private static  AtomicInteger ct =  new AtomicInteger(1);

    public static void main(String[] args) {
        new Thread(() ->{
           while(ct.get() <= 100) {
               lock.lock();
               try {
                   if (ct.get() % 2 != 0) {
                       try {
                           condition.await();
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       };
                   }
                   System.out.println("A");
                   System.out.println(ct.get());
                   ct.incrementAndGet();
                   condition.signalAll();
               } finally {
                    lock.unlock();
               }
           }


        }).start();

        new Thread(() ->{
            while(ct.get() < 100) {
                lock.lock();

                try {
                    if (ct.get() % 2 == 0) {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        };
                    }
                    System.out.println("B");
                    System.out.println(ct.get());
                    ct.incrementAndGet();
                    condition.signalAll();
                } finally {
                    lock.unlock();
                }
            }
        }).start();

    }
}
